package com.rich.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.rich.dao.OrderDao;
import com.rich.domain.Order;
import com.rich.domain.OrderItem;
import com.rich.domain.PageBean;
import com.rich.domain.Product;
import com.rich.utils.DataSourceUtils;

public class OrderDaoImpl implements OrderDao {

	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	/**
	 * 保存订单
	 */
	@Override
	public void saveOrder(Order order) throws Exception {
		String sql = "INSERT INTO orders VALUES(?,?,?,?,?,?,?,?)";
		qr.update(sql,order.getOid(),order.getOrdertime(),
				order.getTotal(),order.getState(),order.getAddress(),
				order.getName(),order.getTelephone(),order.getUser().getUid());
	}

	/**
	 * 保存订单项
	 */
	@Override
	public void saveOrderItem(OrderItem oi) throws Exception {
		String sql = "INSERT INTO orderitem VALUES(?,?,?,?,?)";
		//System.out.println("出现异常");
		qr.update(DataSourceUtils.getConnection(), sql, oi.getItemId(),
				oi.getCount(),oi.getSubtotal(),
				oi.getProduct().getPid(),oi.getOrder().getOid());
	}

	/**
	 * 获取我的订单总条数
	 */
	@Override
	public int getTotalRecore(String uid) throws Exception {
		String sql = "SELECT COUNT(*) FROM orders WHERE uid = ?";
		return ((Long)qr.query(sql, new ScalarHandler(), uid)).intValue();
	}

	/**
	 * 获取我的订单当前页数据
	 */
	@Override
	public List<Order> findMyOrderByPage(PageBean<Order> pb, String uid) throws Exception {
		//查询所有订单基本信息
		String sql = "SELECT * FROM orders WHERE uid = ? ORDER BY ordertime DESC LIMIT ?,?";
		List<Order> list = qr.query(sql, new BeanListHandler<>(Order.class), uid,pb.getStartIndex(),pb.getPageSize());
		//遍历订单,查询每个订单的订单项
		for (Order order : list) {
			sql = "SELECT * FROM product p,orderitem oi WHERE oi.pid = p.pid AND oi.oid = ?";
			List<Map<String, Object>> maplist = qr.query(sql, new MapListHandler(), order.getOid());
			//遍历每个maplist，获取每一个订单项，将其加入到当前订单的订单项列表中
			for (Map<String, Object> map : maplist) {
				//封装成orderitem
				OrderItem oi = new OrderItem();
				//把对应字段的map封装到oi中
				BeanUtils.populate(oi, map);
				//应为map中没有product
				Product p = new Product();
				BeanUtils.populate(p, map);
				oi.setProduct(p);
				//将orderitem放入到order的订单项列表中
				order.getItems().add(oi);
			}
		}
		return list;
	}

	/**
	 * 获取单个订单详情
	 */
	@Override
	public Order getById(String oid) throws Exception {
		//获取指定oid的订单基本信息
		String sql = "SELECT * FROM orders WHERE oid = ?";
		Order order = qr.query(sql, new BeanHandler<>(Order.class), oid);
		
		//查询订单项
		sql = "SELECT * FROM product p,orderitem oi WHERE oi.pid = p.pid AND oi.oid = ?";
		//所有订单项详情
		List<Map<String, Object>> maplist = qr.query(sql, new MapListHandler(), oid);
		//遍历每个订单项，封装到orderitem中
		for (Map<String, Object> map : maplist) {
			//创建orderitem
			OrderItem oi = new OrderItem();
			//封装
			BeanUtils.populate(oi, map);
			//封装product到orderitem
			Product p = new Product();
			BeanUtils.populate(p, map);
			oi.setProduct(p);
			
			//orderitem添加到order中
			order.getItems().add(oi);
		}
		return order;
	}

	/**
	 * 修改订单信息
	 */
	@Override
	public void update(Order order) throws Exception {
		String sql = "UPDATE orders SET state=?,address=?,name=?,telephone=? WHERE oid=?";
		qr.update(sql,order.getState(),order.getName(),order.getAddress(),order.getTelephone(),order.getOid());
	}

	/**
	 * 根据状态获取表单列表
	 */
	@Override
	public List<Order> findAllByState(String state) throws Exception {
		String sql = "SELECT * FROM orders";
		if(state == null || state.trim().length() == 0) {
			sql += " ORDER BY ordertime DESC";
			return qr.query(sql, new BeanListHandler<>(Order.class));
		}
		sql += " WHERE state = ? ORDER BY ordertime DESC";
		return qr.query(sql, new BeanListHandler<>(Order.class), state);
	}

}
